package com.jetpackframework.webview;

import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.frameworkx.layout.frag_webview;
import com.gwm.annotation.layout.Layout;
import com.gwm.annotation.router.ARouter;
import com.jetpackframework.R2;
import com.jetpackframework.base.BaseFragment;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.ProgressCallback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

@Layout(R2.layout.frag_webview)
@ARouter("frameworkx/webviewfragment")
public class WebViewFragment extends BaseFragment<frag_webview> implements WebViewCallBack, SwipeRefreshLayout.OnRefreshListener {
    private String url;
    private LoadService loadService;
    public static Fragment newInstance(String url) {
        Fragment fragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Contracts.URL,url);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding.webview.registerCallBack(this);
        mBinding.webview.loadUrl(url);
        loadService = LoadSir.getDefault().register(mBinding.webview, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mBinding.webview.reload();
            }
        });
        mBinding.swipe_refresh.setOnRefreshListener(this);
        mBinding.webview.addJavascriptInterface(this,"fragment");
    }

    @Override
    public void setArguments(@Nullable Bundle args) {
        super.setArguments(args);
        url = args.getString(Contracts.URL);
    }

    @Override
    public void onPageStarted(WebView view, String url) {
        loadService.showCallback(ProgressCallback.class);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        loadService.showSuccess();
    }

    @Override
    public void onRefresh() {
        mBinding.webview.reload();
        mBinding.swipe_refresh.setRefreshing(false);
    }
    @JavascriptInterface
    public void startActivityForResult(String params){

    }
}
